<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * MySql Driver
 */
class Database_Driver_Mysql {
	private $_link = null;
	private $_qcount = 0;

	/**
	 * Destructor
	 */
	public function __destruct() {
		$this->_disconnect();
	}

	/**
	 * Connecting to database
	 */
	private function _connect() {
		if (!$this->_link) {
			$host = Config::get('host', 'database') . ':' . Config::get('port', 'database');
			$this->_link = mysql_connect($host,
				Config::get('user', 'database'),
				Config::get('password', 'database')
			);

			if ($this->_link) {
				if (mysql_select_db(Config::get('name', 'database'))) {
					mysql_set_charset(Config::get('charset', 'database'), $this->_link);
				} else {
					$this->_error('Can`t select database');
				}
			} else {
				$this->_error('Can`t connect to database');
			}
		}
	}

	/**
	 * Disconnecting from database
	 */
	private function _disconnect() {
		if ($this->_link) {
			mysql_close($this->_link);
		}
	}

	/**
	 * Execute query
	 */
	public function query($sql) {
		$this->_connect();
		if ($this->_link) {
			$this->_qcount++;
			$result = mysql_query($sql, $this->_link);

			if (mysql_errno($this->_link)) {
				$this->_error('Error in query: "' . $sql . '"');
			}

			$driver = ucfirst(trim(strtolower(Config::get('driver', 'database'))));
			$result_class = 'Database_Result_' . $driver;
			$result_obj = new $result_class($result, $this->_link);

			return $result_obj;
		}
	}

	/**
	 * Get last inserted id
	 */
	public function getLastId() {
		return mysql_insert_id($this->_link);
	}
	
	/**
	 * Get affected rows count (INSERT, DELETE, UPDATE)
	 */
	public function getAffectedRows() {
		return mysql_affected_rows($this->_link);
	}

	/**
	 * Return number of executed queries
	 */
	public function getQueryCount() {
		return $this->_qcount;
	}

	/**
	 * Check if error occured
	 */
	public function isError() {
		$result = false;
		
		if (mysql_errno($this->_link) > 0) {
			$result = true;
		} else if ($this->getAffectedRows() == -1) {
			$result = true;
		}
		
		return $result;
	}

	/**
	 * Display error and interrupt executing of script
	 */
	private function _error($str) {
		$errno = 0;
		$errstr = '';

		if ($this->_link && mysql_errno($this->_link)) {
			$errno = mysql_errno($this->_link);
			$errstr = mysql_error($this->_link);
		} else if (mysql_errno()) {
			$errno = mysql_errno();
			$errstr = mysql_error();
		}

		$data = array(
			'errno' => $errno,
			'errstr' => $errstr
		);

		throw new Node_Exception($errstr, $errno);
	}

	/**
	 * Escaping value
	 */
	public function escape($value) {
		$this->_connect();
		return mysql_real_escape_string($value, $this->_link);
	}
}
